const {
  promisify
} = require('util')
const path = require('path')

const download = promisify(require("download-git-repo"))
const open = require("open")

const {
  vueRepo
} = require('../config/repo-config')

const {
  commandSpawn
} = require("../utils/terminal")
const {
  compile,
  writeToFile,
  createDirSync
} = require("../utils/utils")
const createProjectAction = async (project, other) => {
  console.log("install...");
  //1.clone 项目
  await download(vueRepo, project, {
    clone: true
  })
  //2.执行npm i
  const command = process.platform == "win32" ? "npm.cmd" : "npm"
  await commandSpawn(command, ["install"], {
    cwd: `./${project}`
  })
  //执行npm run serve
  commandSpawn(command, ["run", "serve"], {
    cwd: `./${project}`
  })
  //打开浏览器
  open("http://localhost:8080")
}

const addComponentAction = async (name, dest) => {
  //编译ejs模板 
  const result = await compile("vue-component.ejs", {
    name,
    lowerName: name.toLowerCase()
  })
  //写入文件的操作
  const targetPath = path.resolve(dest, `${name}.vue`)
  writeToFile(targetPath, result)
}

const addPageAndRouteAction = async (name, dest) => {
  //编译ejs模板 
  const data = {
    name,
    lowerName: name.toLowerCase()
  }
  const pageResult = await compile("vue-component.ejs", data)
  const routeResult = await compile("vue-router.ejs", data)
  //写入文件的操作
  //判断文件夹是否存在
  const targetDest = path.resolve(dest, name.toLowerCase());
  if (createDirSync(targetDest)) {
    const targetPagePath = path.resolve(targetDest, `${name}.vue`)
    const targetRoutePath = path.resolve(targetDest, `route.js`)
    writeToFile(targetPagePath, pageResult)
    writeToFile(targetRoutePath, routeResult)
  }
}
const addStoreAction = async (name, dest) => {
  const storeResult = await compile("vue-store.ejs", {})
  const typesResult = await compile("vue-types.ejs", {})
  const targetDest = path.resolve(dest, name.toLowerCase());
  if (createDirSync(targetDest)) {
    const targetStorePath = path.resolve(targetDest, `${name}.js`)
    const targetTypesPath = path.resolve(targetDest, `types.js`)
    writeToFile(targetStorePath, storeResult)
    writeToFile(targetTypesPath, typesResult)
  }
}

module.exports = {
  createProjectAction,
  addComponentAction,
  addPageAndRouteAction,
  addStoreAction
}